package visiopuce.ui;

import java.util.List;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import visiopuce.ApplicationContexte;
import visiopuce.objets.Droit;
import visiopuce.objets.Utilisateur;
import visiopuce.service.DroitServiceImpl;
import visiopuce.service.UtilisateurServiceImpl;

public class DroitsUtilisateurDialog extends Dialog {

	private Composite container;

	//TableViewer viewer;

	private Table table;

	private List<Utilisateur> users;

	private int EDITABLECOLUMN;

	public DroitsUtilisateurDialog(Shell parent) {
		super(parent);
		setShellStyle(SWT.CLOSE | SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL);
		setBlockOnOpen(true);
	}

	@Override
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		shell.setText("Modification des droits des utilisateurs");
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		container = (Composite) super.createDialogArea(parent);
		container.setLayout(new GridLayout(1, false));
		if (DroitServiceImpl.getInstance().peutModifierByUtilisateurAndChamp(ApplicationContexte.getInstance().getUtilisateur(), "admin")) {
			// viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL |
			// SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
			// createColumns(parent, viewer);
			// final Table table = viewer.getTable();
			// table.setHeaderVisible(true);
			// table.setLinesVisible(true);
			//
			// viewer.setContentProvider(new CRUDContentProvider());
			// viewer.setLabelProvider(new CRUDLabelProvider());
			// HashMap<String, List<Droit>> droits =
			// DroitServiceImpl.getInstance().getDroits();
			// viewer.setInput(droits);
			table = new Table(parent,  SWT.BORDER | SWT.V_SCROLL
					| SWT.FULL_SELECTION);
			table.setHeaderVisible(true);
			table.setLinesVisible(true); 
			createColumns(parent);
			// Layout the viewer
			GridData gridData = new GridData();
			gridData.verticalAlignment = GridData.FILL;
			gridData.grabExcessHorizontalSpace = true;
			gridData.grabExcessVerticalSpace = true;
			gridData.horizontalAlignment = GridData.FILL;
			table.setLayoutData(gridData);
			createLigne();
			
			final TableEditor editor = new TableEditor(table);
	        //The editor must have the same size as the cell and must
	        //not be any smaller than 50 pixels.
	        editor.horizontalAlignment = SWT.LEFT;
	        editor.grabHorizontal = true;
	        editor.minimumWidth = 50;
	        // editing the second column
	        EDITABLECOLUMN = 1;
	        
	        table.addSelectionListener(new SelectionAdapter() {
	                public void widgetSelected(SelectionEvent e) {
	                        // Clean up any previous editor control
	                        Control oldEditor = editor.getEditor();
	                        if (oldEditor != null) oldEditor.dispose();
	        
	                        // Identify the selected row
	                        final TableItem item = (TableItem)e.item;
	                        if (item == null) return;
	        
	                        // The control that will be the editor must be a child of the Table
	                        Text newEditor = new Text(table, SWT.NONE);
	                        
	                        newEditor.setText(item.getText(EDITABLECOLUMN));
	                        newEditor.addModifyListener(new ModifyListener() {
	                                public void modifyText(ModifyEvent e) {
	                                        Text text = (Text)editor.getEditor();
                                    
	                                        DroitServiceImpl.getInstance().saveCrud(text.getText(), table.getColumn(EDITABLECOLUMN).getText(), item.getText(0));
	                                        
	                                        editor.getItem().setText(EDITABLECOLUMN, text.getText());
	                                }
	                        });
	                        newEditor.selectAll();
	                        newEditor.setFocus();
	                        editor.setEditor(newEditor, item, EDITABLECOLUMN);
	                }
	        });
	        table.addListener(SWT.MouseDown, new Listener(){
	            

				public void handleEvent(Event event){
	                Point pt = new Point(event.x, event.y);
	                TableItem item = table.getItem(pt);
	                if(item != null) {
	                    for (int col = 0; col < table.getColumnCount(); col++) {
	                        Rectangle rect = item.getBounds(col);
	                        if (rect.contains(pt)) {
	                        	EDITABLECOLUMN = col;
	                        }
	                    }
	                }
	            }
	        });
		}
		return container;
	}

	private void createLigne() {
		for (String champ : ApplicationContexte.droits) {
			TableItem ligne1 = new TableItem(table, SWT.NONE);
			String[] ligne = new String[users.size() + 1];
			ligne[0] = champ;
			int i = 1;
			for (Utilisateur u : users) {

				Droit d = DroitServiceImpl.getInstance().getDroitByUtilisateurAndChamp(u, champ);
				if (d != null) {
					ligne[i] = d.getCrud();
				} else {
					ligne[i] = "";
				}
				i++;
			}
			ligne1.setText(ligne);
		}

	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		Button bOk = createButton(parent, IDialogConstants.OK_ID, "OK", true);
		bOk.setToolTipText("Sortir");

	}

	@Override
	protected Point getInitialSize() {
		return new Point(1024, 500);
	}

	@Override
	protected void okPressed() {
		super.okPressed();

	}

	// private void createColumns(final Composite parent, final TableViewer
	// viewer) {
	// List<Utilisateur> users =
	// UtilisateurServiceImpl.getInstance().getUtilisateurs();
	// int i = 0;
	// TableViewerColumn col2 = createTableViewerColumn("Champ", 50, 0);
	// col2.setLabelProvider(new ColumnLabelProvider() {
	// @Override
	// public String getText(Object element) {
	// Droit d = (Droit) element;
	// return d.getChamp();
	// }
	// });
	// i++;
	// for (Utilisateur utilisateur : users) {
	// String init = "";
	// if (utilisateur.getPrenom() != null && utilisateur.getPrenom().length() >
	// 0) {
	// init = utilisateur.getPrenom().substring(0, 1);
	// }
	// TableViewerColumn col = createTableViewerColumn(utilisateur.getNom() +
	// " " + init, 50, i);
	// col.setLabelProvider(new ColumnLabelProvider() {
	// @Override
	// public String getText(Object element) {
	// Droit d = (Droit) element;
	// return d.getCrud();
	// }
	// });
	// col.setEditingSupport(new CRUDEditingSupport(viewer));
	// i++;
	// }
	//
	// }

	private void createColumns(final Composite parent) {
		users = UtilisateurServiceImpl.getInstance().getUtilisateurs();

		TableColumn colonne1 = new TableColumn(table, SWT.LEFT);
		colonne1.setText("Champ");
		colonne1.setWidth(75);
		colonne1.setMoveable(true);

		for (Utilisateur utilisateur : users) {
			String init = "";
			if (utilisateur.getPrenom() != null && utilisateur.getPrenom().length() > 0) {
				init = utilisateur.getPrenom().substring(0, 1);
			}
			TableColumn colonne = new TableColumn(table, SWT.LEFT);
			colonne.setText(utilisateur.getNom() + " " + init);
			colonne.setWidth(75);

		}

	}

	// private TableViewerColumn createTableViewerColumn(String title, int
	// bound, final int colNumber) {
	// final TableViewerColumn viewerColumn = new TableViewerColumn(viewer,
	// SWT.NONE);
	// final TableColumn column = viewerColumn.getColumn();
	// column.setText(title);
	// column.setWidth(bound);
	// column.setResizable(true);
	// column.setMoveable(true);
	//
	// return viewerColumn;
	// }
}
